package com.github.luoshu.open.shiro.redis;

import com.github.luoshu.open.shiro.SuperSessionFactory;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.SessionDAO;

import java.io.Serializable;
import java.util.Collection;

/**
 * @author inme
 */
public class RedisSessionDao implements SessionDAO {


    private RedisManager redisManager;

    private SuperSessionFactory superSessionFactory;

    public RedisSessionDao(SuperSessionFactory superSessionFactory) {
        this.superSessionFactory = superSessionFactory;
        this.redisManager = superSessionFactory.getRedisManager();
    }

    @Override
    public Serializable create(Session session) {
        int sessionTimeMinute = ((RedisSession)session).getSessionTimeMinute();

        String key = RedisSession.getRedisSessionKey((String) session.getId());
        redisManager.putHash(key , RedisSession.SESSION_CREATE_TIME , System.currentTimeMillis());
        redisManager.putHash(key , RedisSession.SESSION_LAST_ACCESS_TIME , System.currentTimeMillis());
        redisManager.putHash(key , RedisSession.SESSION_HOST , session.getHost());
        redisManager.putHash(key , RedisSession.SESSION_TIMEOUT_MINUTE , sessionTimeMinute);
        redisManager.expire(key , sessionTimeMinute * 60 * 1000);

        return session.getId();
    }

    @Override
    public Session readSession(Serializable sessionId) throws UnknownSessionException {
        return new RedisSession((String) sessionId, redisManager, superSessionFactory.getSessionTimeMinute());
    }

    @Override
    public void update(Session session) throws UnknownSessionException {
        //nothing
    }

    @Override
    public void delete(Session session) {
        redisManager.deleteKey((String) session.getId());
    }

    @Override
    public Collection<Session> getActiveSessions() {
        // 未实现，基于性能考虑
        return null;
    }



}
